<template>
  <div class="product-manager-warp disabled-warp" style="height: calc(100% - 10px); padding: 20px; ">
    <div class="dashboard-container"
         style=" padding: 20px 25px 10px;  ">
      <div
          style="line-height: 16px; flex-wrap: wrap; width: 100%; display: flex;  align-items: center;  font-size: 16px; font-family: Source Han Sans CN;font-weight: bold;color: #2F3745; ">
        <div class="dashboard-inner" style="width: 200px;">
          应收欠款
          <el-tooltip class="item" effect="dark" content="温馨提示：对应列可以通过拖动改变表格宽度" placement="top">
            <i style="position: relative; left: 6px; top: 2px;" class="header-icon el-icon-info"></i>
          </el-tooltip>
        </div>
        <div style="width: calc(100% - 200px); display: flex; position: relative; top: -7px; justify-content: center;">
          <common-operation-form :list="statisticList" :marginRight="'112px'"/>
        </div>
      </div>
    </div>

    <div style="display: flex; height: calc(100% - 105px);">
      <div class="right-content2" style="background: #fff; " :style="`  'width: 100%; margin-left: 0;' `">
        <div class="product-inventory-table"
             :style="`margin-left: 12px; margin-right: 12px; height: 100%; width: calc(100% - 24px);`">
          <div style="display: flex; position: relative;">
            <common-operation-form :list="list"/>
            <common-operation-form :list="list2" :margin-right="'0px'"
                                   style="position: absolute; height: 38px; top: 2px; cursor: pointer;   right: 0;"/>
          </div>
          <el-table style="margin-top: 15px; " fit :height="windowHeight - 50"
                    @select="changeevent" ref="tableRef" @cell-click="tableRowClick"
                    v-loading="table.loading" :data="table.data" border >

            <template v-for="(item, index) in table.header1">
              <el-table-column :prop="item.prop" :key="index" :show-overflow-tooltip="true"
                               :width="item.width || 'auto'" :align="`center`"
                               :label="item.label">
                <template slot-scope="scope">
                  <span v-if="item.prop === 'createDate'" style=" ">
                    {{ parseTime(new Date(scope.row[item.prop])) }}
                  </span>
                  <span v-else :style="`color: ${item.color ? item.color : ''}`">
                    {{ item.keepTwoDecimal ? keepTwoDecimalFull(scope.row[item.prop]) : scope.row[item.prop] }}
                  </span>
                </template>
              </el-table-column>
            </template>

            <el-table-column
                label="操作" width="190" fixed="right">
              <template slot-scope="scope">
                <div style="display: flex;" v-if="!scope.row.children || scope.row.children.length <= 0">
                  <el-button size="mini" class="minimini" @click="detail(scope.row)" type="success">详情</el-button>
                  <el-button size="mini" class="minimini" @click="detail(scope.row)" type="primary">发送对账单</el-button>
                  <el-button size="mini" class="minimini" @click="payment(scope.row)" type="primary">付款</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination style="position: relative; text-align: right; margin-top: 10px;" @size-change="sizeChange"
                         @current-change="currentChange"
                         :current-page="page.pageNumber"
                         layout="sizes, jumper, prev, pager, next" :page-size="page.pageSize"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>


    <el-dialog style="margin-top: 10px;"
               :close-on-click-modal="false"
               width="95%" v-dialog-drag :modal="false"
               custom-class="dialoginter7"
               :visible.sync="dialog.dialogVisible">
      <span slot="title" v-if="dialog.chooseItem">
        {{ dialog.chooseItem['customerName'] }}的应收欠款详情
        <common-operation-form :margin-right="0" :list="list3"
                               style=" float: right; position: absolute; margin-bottom: 6px; top: 4px; cursor: pointer;   right: 32px;"/>
      </span>

      <span>
        <common-operation-form
            style=" border-radius: 6px; padding: 10px 0 10px 15px; margin-top: 10px; background: #f5f6f7;"
            :list="dialog.statisticList" :marginRight="'112px'"/>
        <el-table style="margin-top: 15px; " fit :height="windowHeight - 10"
                  show-summary :summary-method="getSummaries2" ref="tableRef2"
                  v-loading="dialog.loading" :data="dialog.data" border >
            <template v-for="(item, index) in dialog.header1">
              <el-table-column :prop="item.prop" :key="index" :show-overflow-tooltip="true"
                               :width="item.width || 'auto'" :align="`center`"
                               :label="item.label">
                <template slot-scope="scope">
                  <span v-if="item.prop === 'createDate'" style=" ">
                    {{ parseTime(new Date(scope.row[item.prop])) }}
                  </span>
                  <span v-else-if="item.prop === 'documentNumber'" @click="toDetail(scope.row)" :class="[documentNumberNotClick(scope.row['typeName']) ? 'clickable-class' : '']" style="font-weight: 500;  ">
                    {{ scope.row[item.prop] }}
                  </span>
                  <span v-else :style="`color: ${item.color ? item.color : ''}`">
                    {{ item.keepTwoDecimal ? keepTwoDecimalFull(scope.row[item.prop]) : scope.row[item.prop] }}
                  </span>
                </template>
              </el-table-column>
            </template>
        </el-table>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonOperationForm from "@/components/CommonOperationForm/index.vue";
import CommonDialogForm from "@/components/CommonDialogForm/index.vue";
import TreeExpansion from "@/components/TreeExpansion/ProductManager.vue";
import {
  accountsReceivableOverview,
  getAccountsReceivableList,
  getAccountsReceivableDetailByID
} from "@/api/accountsReceivable";
import {getUserInfo} from "@/utils/auth";
import {
  documentTypeOptions,
  findRowByID,
  formatAmount,
  isNotANumberOrEmpty,
  keepTwoDecimalFull,
  parseTime,
  calculateTwoValue,
} from "../../utils";
import UnitSelect from "@/components/Unit/UnitSelect.vue";
import WarehouseSelect from "@/components/Warehouse/WarehouseSelect.vue";

export default {
  name: 'accounts_receivable',
  components: {WarehouseSelect, UnitSelect, CommonOperationForm, CommonDialogForm, TreeExpansion},
  data() {
    return {
      statisticList: [
        {
          type: 'statistic',
          title: '期初欠款',
          iconClass: 'plus2',
          value: 0,
        },
        {
          type: 'statistic',
          title: '增加应收欠款',
          iconClass: 'minus',
          value: 0,
        },
        {
          type: 'statistic',
          title: '收回欠款',
          iconClass: 'equal',
          value: 0,
        },
        {
          type: 'statistic',
          title: '应收欠款',
          value: 0,
        },
      ],
      list: [
        {
          type: 'input',
          text: '客户姓名：',
          width: '85px',
          value: '',
        },
        {
          type: 'input',
          text: '客户编号：',
          width: '95px',
          value: '',
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-search',
          buttonText: '搜索',
          event: () => {
            this.pageNumber = 1;
            this.requestApi();
          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-document-add',
          buttonText: '导入',
          event: () => {

          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-takeaway-box',
          buttonText: '导出',
          event: () => {

          }
        },
        {
          type: 'checkbox',
          name: '显示无欠款的客户',
          value: false,
          changeEvent: (v) => {
            console.log(v);
            this.page.pageNumber = 1;
            this.requestApi();
          },
        },
      ],
      list2: [
        {
          type: 'refresh',
          loading: false,
          iconClass: 'refresh3',
          clickEvent: () => {
            if (this.list2[0].loading)
              return;
            this.list2[0].loading = true;
            this.accountsReceivableOverview();
            this.requestApi();
          }
        },
      ],
      list3: [
        {
          type: 'refresh2',
          loading: false,
          iconClass: 'refresh',
          clickEvent: () => {
            if (this.list3[0].loading)
              return;
            this.list3[0].loading = true;
            this.detail(this.dialog.chooseItem);
          }
        },
      ],
      treeCurrentNodeKey: '',
      table: {
        data: [],
        loading: false,
        header1: [
          {
            "prop": "customerName",
            "label": "客户",
            width: '150px',
          },
          {
            "prop": "ContactPerson",
            width: '140px',
            "label": "联系人"
          },
          {
            "prop": "Telephone",
            "label": "联系电话"
          },
          {
            "prop": "initialDebtOwed",
            "label": "期初欠款",
            keepTwoDecimal: true,
          },
          {
            "prop": "addPayableAmount",
            "label": "增加应收欠款",
            keepTwoDecimal: true,
          },
          {
            "prop": "paidAmount",
            "label": "收回欠款",
            keepTwoDecimal: true,
          },
          {
            "prop": "totalPayableAmount",
            color: "red",
            "label": "应收欠款",
            keepTwoDecimal: true,
          },
        ],
        rowSelect: -1,
      },
      dialog: {
        col: 3,
        chooseItem: null,
        dialogVisible: false,
        loading: false,
        data: [],
        header1: [
          {
            "prop": "createDate",
            "label": "业务日期",
            width: '140px',
          },
          {
            "prop": "documentNumber",
            width: '140px',
            "label": "单据编号",
          },
          {
            "prop": "typeName",
            "label": "业务类型"
          },
          // {
          //   "prop": "payableAmount",
          //   "label": "原单价格",
          //   color: "#1362fc",
          //   keepTwoDecimal: true,
          // },
          {
            "prop": "unpaidAmount",
            "label": "原单欠款",
            color: "red",
            keepTwoDecimal: true,
          },
          {
            "prop": "paidAmount",
            "label": "付款",
            color: "red",
            keepTwoDecimal: true,
          },
          // {
          //   "prop": "",
          //   "label": "优惠",
          // },
          {
            "prop": "unpaidAmount",
            "label": "应收欠款",
            color: "red",
            keepTwoDecimal: true,
          },
          {
            "prop": "currentUnpaidAmount",
            "label": "当前欠款",
            keepTwoDecimal: true,
            color: "red",
          },
          {
            "prop": "remarks",
            "label": "备注",
          },
        ],
        statisticList: [
          {
            type: 'statistic',
            title: '期初欠款',
            iconClass: 'plus2',
            value: 0,
          },
          {
            type: 'statistic',
            title: '增加应收欠款',
            iconClass: 'minus',
            value: 0,
          },
          {
            type: 'statistic',
            title: '收回欠款',
            iconClass: 'equal',
            value: 0,
          },
          {
            type: 'statistic',
            title: '应收欠款',
            value: 0,
          },
        ],
        formData: null,
      },
      page: {
        pageSize: 10,
        pageNumber: 1,
        total: 0,
      }
    }
  },
  mounted() {
    this.accountsReceivableOverview();
    this.requestApi();
  },
  methods: {
    formatAmount,
    parseTime,
    keepTwoDecimalFull,
    isNotANumberOrEmpty,
    toDetail(item) {
      console.log(item);
      if (item.typeName.indexOf("收款") !== -1) {
        this.$router.push({
          path: "/financial_statements/add_accounts_payable_detail/" +  item._id,
        });
      } else if (item.typeName.indexOf("销售") !== -1) {
        this.$router.push({
          path: "/sale_manager/product_sale_detail/" +  item._id,
        });
      }
    },
    accountsReceivableOverview() {
      accountsReceivableOverview({
        userID: getUserInfo().userID,
      }).then(res => {
        console.log(res);
        this.statisticList[0].value = parseFloat(res.data.data.totalInitialDebtOwed);
        this.statisticList[1].value = parseFloat(res.data.data.totalAddPaidAmount);
        this.statisticList[2].value = parseFloat(res.data.data.totalPaidAmount);
        this.statisticList[3].value = parseFloat(res.data.data.totalUnpaidAmount);
      });
    },
    requestApi() {
      if (this.table.loading)
        return;
      this.table.loading = true;

      getAccountsReceivableList({
        pageSize: this.page.pageSize,
        pageNumber: this.page.pageNumber,
        userID: getUserInfo().userID,
        customerName: this.list[0].value,
        customerNumber: this.list[1].value,
        arrears: this.list[5].value ? 0 : 1,
      }).then(res => {
        if (res.data.code === -1) {
          this.$message.error(res.data.errMsg);
          return;
        }

        this.table.data = res.data.data;
        this.page.total = res.data.page.totalDocuments;
        this.$nextTick(() => {
          this.table.loading = false;
          this.list2[0].loading = false;
        });
      });
    },
    tableRowClick(row, column, cell, event) {
      let {id} = row;
      this.rowSelect = findRowByID(this.table.data, id);
      this.$refs.tableRef.setCurrentRow(this.table.data[this.rowSelect]);
      // console.log(this.$refs.tableRef, this.rowSelect);
    },
    payment(item) {
      console.log(item);
      this.$router.push({path: "/financial_statements/add_accounts_payable", query: {_id: item._id}})
    },
    detail(item) {
      this.dialog.chooseItem = item;
      this.dialog.dialogVisible = true;

      this.dialog.loading = true;
      this.dialog.statisticList[0].value = parseFloat(keepTwoDecimalFull(item.initialDebtOwed));
      this.dialog.statisticList[1].value = parseFloat(keepTwoDecimalFull(item.addPayableAmount));

      getAccountsReceivableDetailByID({
        customerID: item._id,
        userID: getUserInfo().userID,
      }).then(res => {
        this.dialog.data = res.data.data;

        this.$nextTick(() => {
          this.dialog.loading = false;
          this.list3[0].loading = false;
        });
      });
    },
    sizeChange(val) {
      console.log(this.page);
      this.page.pageSize = val;
      this.page.pageNumber = 1;
      this.requestApi();
    },
    currentChange(val) {
      this.page.pageNumber = val;
      this.requestApi();
    },
    changeevent(selection, row) {
      console.log(selection, row);

    },
    getSummaries2(param) {
      const {columns, data} = param;
      const sums = [];

      let totalUnpaidAmount = 0;
      let totalPayAmount = 0.0;
      let currentUnpaidAmount = 0;
      for (let i = 0; i < data.length; i++) {
        let {unpaidAmount, totalPayMoney,} = data[i];
        if (i === 0) {
          currentUnpaidAmount = data[i].currentUnpaidAmount;
        }

        totalPayAmount = calculateTwoValue(totalPayAmount, totalPayMoney, 'add');
        totalUnpaidAmount = calculateTwoValue(unpaidAmount, totalUnpaidAmount, 'add');
      }

      columns.forEach((column, index) => {
        let {label} = column;
        if (label === '付款') {
          sums[index] = `${keepTwoDecimalFull(totalPayAmount)}`;
          this.dialog.statisticList[2].value = parseFloat(keepTwoDecimalFull(totalPayAmount));
        } else if (label === '原单欠款' || label === '应收欠款') {
          sums[index] = `${keepTwoDecimalFull(totalUnpaidAmount)}`;
        } else if (label === '当前欠款') {
          console.log("currentUnpaidAmount: ", currentUnpaidAmount);
          this.dialog.statisticList[3].value = parseFloat(keepTwoDecimalFull(currentUnpaidAmount));
          sums[index] = `欠款：${keepTwoDecimalFull(currentUnpaidAmount)}`;
        } else {
          sums[index] = '';
        }
      });

      this.$nextTick(() => {
        this.$refs.tableRef2.doLayout();
      });
      return sums;
    },
    setRowClass({row, rowIndex}) {
      if (row.id === this.rowSelect) {
        return 'table-current-row';
      }
      return '';
    },
    submit() {
      let data = this.$refs.commondialogformref.requiredEmpty();
      if (data) {
        this.$message.error(data.requiredMessage);
        return;
      }

      data = this.$refs.commondialogformref.getData();
      data['isDisabled'] = false;
      this.dialog.form = JSON.parse(JSON.stringify(this.dialog.copyForm));
      this.table.data.push(data);
      this.$message.success("添加成功");
    }
  }
}
</script>


<style lang="scss">
.dashboard {
  &-container {
    background: #fff;
    box-shadow: 0px 0px 10px 0px rgba(45, 51, 65, 0.08);
    border-radius: 10px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.dashboard-inner {
  font-size: 16px;
  font-weight: 700;
  padding: 0 0 10px 0;
  color: #2f3745;
}


.el-scrollbar__view {
  height: 100%;
}

.el-scrollbar__wrap {
  overflow: scroll;
}

.box-card .el-card__body {
  height: 100%;
}

.left-content {
  line-height: 16px;
  flex-wrap: wrap;
  border-radius: 10px;
  display: flex;
  padding-top: 10px;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
}


.right-content2 {
  line-height: 16px;
  flex-wrap: wrap;
  width: calc(100% - 0px);
  border-radius: 10px;
  display: flex;
  padding-top: 10px;
  margin-top: 10px;
  margin-left: 10px;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
}

.table-product-hover {
  cursor: pointer;
}

.table-product-hover:hover {
  text-underline: #3A71A8;
  text-decoration: underline;
}

.clickable-class:hover {
  opacity: 0.7;
}

.clickable-class {
  cursor: pointer;
  color: rgb(64, 158, 255) !important;
}
</style>
